--
-- Author: shunguo.chen
-- Date: 2018-05-16 12:49:50
--
-- RollNoticeView
--

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ViewBase)

ClassRef.VIEW_ROOT_RES = Res.RollNoticeScene

local TIME_PER_DIS = 100

function ClassRef:init()
	local text = self._root:findChild("Panel/Text")
	local fontSize = text:getFontSize()
	local fontColor = text:getTextColor()
	text:removeFromParent()

	self._ui.Panel:setTouchEnabled(false)

	local defaults = {}
	-- defaults["KEY_FONT_FACE"] = Res.font
	defaults["KEY_FONT_SIZE"] = fontSize
	defaults["KEY_FONT_COLOR_STRING"] = display.stringWithColor(fontColor)
	self._defaults  = defaults

	local size = self._ui.Panel:getContentSize()
	self._panelWidth = size.width
	self._textPosY = size.height / 2

	display.setCascadeOpacityEnabled(self, true)

	self._notices = {}
end

function ClassRef:show()
	if #self._notices == 0 then return end
	self.super.show(self)

	self:refresh()
end

function ClassRef:hide()
	self.super.hide(self)

	if self._richText and self._moveAct then
		self._richText:stopAction(self._moveAct)
	end
end

function ClassRef:refresh()
	local text = self._richText
	if text and self._moveAct then
		text:stopAction(self._moveAct)
	end

	if not text then
		text = ccui.RichText:createWithXML(self._notices[1].content, self._defaults)
		text:setEnabled(false)
		text:setTouchEnabled(false)
		text:setAnchorPoint(cc.p(0,0.5))
		display.setCascadeOpacityEnabled(text, true)

		text:setOpenUrlHandler(function() end)
		text:formatText()

		local textSize = text:getFormatSize()
		text:setContentSize(textSize)

		self._ui.Panel:addChild(text)
		text:setPosition(self._panelWidth, self._textPosY)

		self._richText = text
		self._textWidth = textSize.width
	end

	local curPosX = text:getPositionX()
	local dis = curPosX + self._textWidth
	local duration = dis / TIME_PER_DIS
	local move = cca.moveTo(duration, -self._textWidth, self._textPosY)
	local cb = cca.cb(function()
			self:_checkNext()
		end)
	local action = cca.seq({move, cb})
	text:runAction(action)
	self._moveAct = action
end

function ClassRef:_checkNext()
	self._richText:removeFromParent()
	self._richText = nil
	self._moveAct = nil

	table.remove(self._notices, 1)
	if #self._notices > 0 then
		table.sort(self._notices, function(a, b)
			return a.priority < b.priority
		end)
		self:refresh()
	else
		self:setVisible(false)
	end
end

function ClassRef:addNotice(notices)
	if not notices then return end
	for i,notice in ipairs(notices) do
		self._notices[#self._notices + 1] = notice
	end
end

return ClassRef
